package com.abu.gatewayms.config;

import com.abu.gatewayms.properties.JwtProperties;
import com.abu.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@Component
@EnableConfigurationProperties(JwtProperties.class)
public class CheckLoginGatewayFilter implements GatewayFilter {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
//        获取cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        List<HttpCookie> httpCookies = cookies.get(jwtProperties.getCookieName());
//        判断cookie是否为空
        if (CollectionUtils.isEmpty(httpCookies)) {
//            拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

//        遍历解析cookie(只要有一个能正常解析，返回true,否则返回false)
        boolean flag = httpCookies.stream().anyMatch(httpCookie -> {
            Map<String, Object> info = null;
            try {
                info = JwtUtils.getInfoFromToken(httpCookie.getValue(), jwtProperties.getPublicKey());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!CollectionUtils.isEmpty(info)) {
                return true;
            }
            return false;
        });
        if (!flag) {
//            拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }
}
